package com.caesar.gxmz;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.Span;
import org.htmlparser.tags.TitleTag;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.HtmlPage;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

@SuppressLint("JavascriptInterface")
public class ShareTwoActivity extends Activity {
	private ProgressDialog progressDialog = null;
	private WebView webview;
	private LinearLayout rl_titile_bar_right;
	private static String shareUrl = "https://www.fdcanet.com/index.php?app=agent&id=1111111119&act=new_articles&appid=1";
	private Map<String, String> shareMap = new HashMap<String, String>();

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				progressDialog.show();
				GetVersionTask task1 = new GetVersionTask();
				task1.execute();
				break;
			case 2:

				break;
			case 3:

				break;
			}
		}
	};

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_share);
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("请耐心等待...");
		shareUrl = getIntent().getStringExtra("shareUrl");
		webview = (WebView) findViewById(R.id.activity_buy_share_webview);

		rl_titile_bar_right = (LinearLayout) this
				.findViewById(R.id.rl_titile_bar_right);
		rl_titile_bar_right.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				showShare(ShareTwoActivity.this, shareMap, null, false);
			}
		});

		// 首页
		ImageView btnBack = (ImageView) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				//
				finish();

			}
		});
		ShareSDK.initSDK(this);
		// 设置WebView属性，能够执行Javascript脚本
		WebSettings webSettings = webview.getSettings();
		// 设置js可用
		webSettings.setJavaScriptEnabled(true);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
		webSettings.setSupportZoom(true);
		webSettings.setBuiltInZoomControls(false);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		webSettings.setDomStorageEnabled(true);
		webSettings.setDatabaseEnabled(true);
		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

		// 添加js调用接口
		webview.loadUrl(shareUrl);
		handler.sendEmptyMessage(1);
		webview.setWebViewClient(new MyWebViewClient());
	}

	// Web视图
	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// shareUrl = url;
			// view.loadUrl(url);
			return true;
		}

	}

	public void onResume() {
		super.onResume();

	}

	public void onPause() {
		super.onPause();

	}

	class GetVersionTask extends AsyncTask<String, String, Map<String, String>> {

		protected Map<String, String> doInBackground(String... param) {
			try {
				shareMap = parserDwPost();
			} catch (ParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return shareMap;
		}

		protected void onPostExecute(Map<String, String> result) {
			progressDialog.dismiss();
			rl_titile_bar_right.setVisibility(View.VISIBLE);
		}
	}

	private Map<String, String> parserDwPost() throws ParserException {
		Map<String, String> postMap = new HashMap<String, String>();
		// 创建 html parser 对象，并指定要访问网页的 URL 和编码格式
		Parser htmlParser = new Parser(shareUrl);
		htmlParser.setEncoding("UTF-8");
		HtmlPage visitor = new HtmlPage(htmlParser);
		htmlParser.visitAllNodesWith(visitor);
		String headTitle = visitor.getTitle();
		postMap.put("headTitle", headTitle);
		Parser html2Parser = new Parser(shareUrl);
		html2Parser.setEncoding("UTF-8");
		NodeList mainNode = html2Parser.extractAllNodesThatMatch(new AndFilter(
				new TagNameFilter("div"), new HasAttributeFilter("class",
						"article_text")));
		if (mainNode != null && mainNode.size() > 0) {
			// 获取指定 div 标签的子节点中的 <li> 节点
			NodeList itemLiListP = mainNode.elementAt(0).getChildren()
					.extractAllNodesThatMatch(new TagNameFilter("P"), true);
			if (itemLiListP != null && itemLiListP.size() > 0) {
				// 在 <li> 节点的子节点中获取 Link 节点
				for (int i = 0; i < 3; i++) {
					NodeList titleItem = itemLiListP
							.elementAt(i)
							.getChildren()
							.extractAllNodesThatMatch(
									new NodeClassFilter(Span.class), true);
					NodeList imageItem = titleItem
							.elementAt(0)
							.getChildren()
							.extractAllNodesThatMatch(
									new NodeClassFilter(ImageTag.class), true);
					if (imageItem != null && imageItem.size() > 0) {
						String imageURL = ((ImageTag) imageItem.elementAt(0))
								.getImageURL();
						postMap.put("imageURL", imageURL);
					} else if (titleItem != null && titleItem.size() > 0) {
						String titleString = ((Span) titleItem.elementAt(0))
								.getSpanTagitem();
						postMap.put("titleString", titleString);
					}
				}

			}

		}
		return postMap;
	}

	/**
	 * 演示调用ShareSDK执行分享
	 * 
	 * @param context
	 * @param platformToShare
	 *            指定直接分享平台名称（一旦设置了平台名称，则九宫格将不会显示）
	 * @param showContentEdit
	 *            是否显示编辑页
	 */
	public static void showShare(Context context, Map<String, String> showMap,
			String platformToShare, boolean showContentEdit) {
		OnekeyShare oks = new OnekeyShare();
		oks.setSilent(!showContentEdit);
		if (platformToShare != null) {
			oks.setPlatform(platformToShare);
		}
		// ShareSDK快捷分享提供两个界面第一个是九宫格 CLASSIC 第二个是SKYBLUE
		oks.setTheme(OnekeyShareTheme.CLASSIC);
		// 令编辑页面显示为Dialog模式
		oks.setDialogMode();
		// 在自动授权时可以禁用SSO方式
		oks.disableSSOWhenAuthorize();
		// oks.setAddress("12345678901"); //分享短信的号码和邮件的地址
		String headTitle = showMap.get("headTitle");
		String titleString = showMap.get("titleString");
		String imageURL = showMap.get("imageURL");
		oks.setTitle(headTitle);
		oks.setTitleUrl(shareUrl);
		oks.setText(titleString);
		// oks.setImagePath("/sdcard/test-pic.jpg"); //分享sdcard目录下的图片
		oks.setImageUrl(imageURL);
		oks.setUrl(shareUrl); // 微信不绕过审核分享链接
		// oks.setFilePath("/sdcard/test-pic.jpg");
		// //filePath是待分享应用程序的本地路劲，仅在微信（易信）好友和Dropbox中使用，否则可以不提供
		oks.setComment("今天就注册，使用我们的免费服务。"); // 我对这条分享的评论，仅在人人网和QQ空间使用，否则可以不提供
		oks.setSite("易美居"); // QZone分享完之后返回应用时提示框上显示的名称
		oks.setSiteUrl(shareUrl);// QZone分享参数
		oks.setVenueName("易美居");
		oks.setVenueDescription(titleString);
		// 将快捷分享的操作结果将通过OneKeyShareCallback回调
		// oks.setCallback(new OneKeyShareCallback());
		// 去自定义不同平台的字段内容
		// oks.setShareContentCustomizeCallback(new
		// ShareContentCustomizeDemo());
		// 在九宫格设置自定义的图标
		Bitmap logo = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.ic_launcher);
		String label = "易美居";
		OnClickListener listener = new OnClickListener() {
			public void onClick(View v) {

			}
		};
		oks.setCustomerLogo(logo, label, listener);

		// 为EditPage设置一个背景的View
		// oks.setEditPageBackground(getPage());
		// 隐藏九宫格中的新浪微博
		// oks.addHiddenPlatform(SinaWeibo.NAME);

		// String[] AVATARS = {
		// "http://99touxiang.com/public/upload/nvsheng/125/27-011820_433.jpg",
		// "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339485237265.jpg",
		// "http://diy.qqjay.com/u/files/2012/0523/f466c38e1c6c99ee2d6cd7746207a97a.jpg",
		// "http://diy.qqjay.com/u2/2013/0422/fadc08459b1ef5fc1ea6b5b8d22e44b4.jpg",
		// "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339510584349.jpg",
		// "http://diy.qqjay.com/u2/2013/0401/4355c29b30d295b26da6f242a65bcaad.jpg"
		// };
		// oks.setImageArray(AVATARS); //腾讯微博和twitter用此方法分享多张图片，其他平台不可以

		// 启动分享
		oks.show(context);
	}

}
